package my.georings.data;

import java.util.ArrayList;
import java.util.Comparator;

import my.georings.GeoPhoneRingsApp;
import my.georings.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.app.Activity;

public class LocationManagerAdapter extends ArrayAdapter<MyLocation>{
	
	private Context context;
	
	public LocationManagerAdapter(Context context, int textViewResourceId, ArrayList<MyLocation> items) {
        super(context, textViewResourceId, items);
        this.context = context;
        this.sortByName();
	}
	
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        MyLocation location = getItem(position);
        if (location != null) {
        	ToggleButton onoff = (ToggleButton) v.findViewById(R.id.ItemToggleButtonLocationOn);
        	TextView name = (TextView) v.findViewById(R.id.ItemTextViewLocationName);
        		
            onoff.setChecked(location.isON());
            name.setText(location.getName());
            
            onoff.setContentDescription(location.getId()+"");
            
            onoff.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String id = v.getContentDescription().toString();
					GeoPhoneRingsApp app = (GeoPhoneRingsApp) ((Activity)LocationManagerAdapter.this.context).getApplication();
					MyLocation loc = app.getMyLocationsManager().getLocationOfId(Integer.valueOf(id));
					loc.setONnotifyParent(((ToggleButton)v).isChecked());
				}
			});
        }
        
        return v;
    }
	
	
	public void sortByName(){
		sort(new Comparator<MyLocation>() {
	    	public int compare(MyLocation object1, MyLocation object2) {
	    		return object1.getName().toLowerCase().compareTo(object2.getName().toLowerCase());
	    	};
    });
}
	


}
